import json

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from model.models import UserInfo


def hello(request):
    return HttpResponse("Hello World!")


def runoob(request):
    request.encoding = "utf-8"
    context = {}
    context["hello"] = "Hello World!"
    views_name = "菜鸟教程"
    # 第三个参数是响应
    return render(request, "runoob.html", {"name": views_name})


@require_http_methods(["GET"])
def userInfo(request):
    request.encoding = "utf-8"
    user_dict = UserInfo.objects.get(id=1).__to_dic__()
    print("查询结果：", user_dict)
    return JsonResponse(user_dict)


@require_http_methods(["GET"])
def findById(request, user_id: int):
    request.encoding = "utf-8"
    user_dict = UserInfo.objects.get(id=user_id).__to_dic__()
    print("查询结果：", user_dict)
    return JsonResponse(user_dict)


@require_http_methods(["GET"])
def findByUsername(request):
    request.encoding = "utf-8"
    username = request.GET.get("username")
    print("查询结果：", username)
    return HttpResponse(username)


@require_http_methods(["POST"])
@csrf_exempt
def findByCondition1(request):
    request.encoding = "utf-8"
    username = request.POST.get("username")
    print("查询结果：", username)
    return HttpResponse(username)


@require_http_methods(["POST"])
@csrf_exempt
def findByCondition(request):
    request.encoding = "utf-8"
    content = json.loads(request.body.decode())
    # body 默认是字符串需要先转成JSON
    print("查询结果：", content)
    return JsonResponse(content)
